#define _CRT_SECURE_NO_WARNINGS 1

#include "SLlist.h"



void SLTPrint(SLNode* plist)
{
	SLNode* cur = plist;
	while (cur != NULL)
	{
		printf("%d->", cur->val);
		cur = cur->next;
	}
	printf("\n");
}


SLNode* BuySLTNode(SLTData x)
{
	SLNode* newNode=(SLNode*)malloc(sizeof(SLNode));
	if (newNode == NULL)
	{
		perror("malloc fail!");
		exit(-1);
	}
	newNode->val = x;
	newNode->next = NULL;
	return newNode;
}




void SLTPushBack(SLNode** pplist, SLTData x)
{
	SLNode* newNode = BuySLTNode(x);
	if (*pplist == NULL)
	{
		*pplist=newNode;
	}
	else
	{
		SLNode* tail = *pplist;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = newNode;
	}
}


void SLTPushFront(SLNode** pplist, SLTData x)
{
	SLNode* newNode = BuySLTNode(x);
	newNode->next = *pplist;
	*pplist = newNode;
}




void SLTPopBack(SLNode** pplist)
{
	assert(*pplist);

	if ((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
	}

	else
	{
		SLNode* tail = *pplist;
		while (tail->next->next != NULL)
		{
			tail = tail->next;
		}
		free(tail->next);
		tail->next = NULL;
	}
}


void SLTPopFront(SLNode** pplist)
{
	assert(*pplist);

	SLNode* tmp = *pplist;
	*pplist = (*pplist)->next;
	free(tmp);
	
}


SLNode* SLTFind(SLNode* plist, SLTData x)
{
	SLNode* cur = plist;
	while (cur)
	{
		if (cur->val == x)
		{
			return cur;
		}
		else
		{
			cur = cur->next;
		}
	}
	return NULL;
}

void SLTInsertAfter(SLNode* pos, SLTData x)
{
	assert(pos);
	SLNode* newnode =BuySLTNode(x);

	newnode->next = pos->next;
	pos->next = newnode;
}


void SLTEraseAfter(SLNode* pos)
{
	assert(pos);
	assert(pos->next);
	SLNode* tmp = pos;
	pos->next = pos->next->next;
	free(tmp);
	tmp = NULL;
}


void SLTInsert(SLNode** pphead, SLNode* pos, SLTData x)
{
	assert(*pphead);
	assert(pos);
	assert(pphead);

	if (*pphead == pos)
	{
		SLTPushFront(pphead, x);
	}
	else
	{
		SLNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}

		SLNode* newnode =BuySLTNode(x);
		prev->next = newnode;
		newnode->next = pos;
	}
}


void SLTErase(SLNode** pphead, SLNode* pos)
{
	assert(*pphead);
	assert(pos);
	assert(pphead);

	if (*pphead == pos)
	{
		SLTPopFront(pos);
	}
	else
	{
		SLNode* prev = *pphead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = pos->next;
		free(pos);
		pos = NULL;
	}
}

void SLTDestroy(SLNode** pphead)
{
	assert(pphead);

	SLNode* cur = *pphead;
	while (cur)
	{
		SLNode* next = cur->next;
		free(cur);
		cur = next;
	}

	*pphead = NULL;
}